<script lang="ts" context="module">
  async function openArchive(fileName, folderName) {
    openNewTab({
      title: fileName,
      icon: 'img archive',
      tooltip: `${folderName}\n${fileName}`,
      tabComponent: 'ArchiveFileTab',
      props: {
        archiveFile: fileName,
        archiveFolder: folderName,
      },
    });
    // }
  }

  async function openTextFile(fileName, fileType, folderName, tabComponent, icon) {
    const connProps: any = {};
    let tooltip = undefined;
    const isZipped = folderName.endsWith('.zip');

    const resp = isZipped
      ? await apiCall('files/download-text', { uri: `zip://archive:${folderName}//${fileName}.jsonl` })
      : await apiCall('files/load', {
          folder: 'archive:' + folderName,
          file: fileName + '.' + fileType,
          format: 'text',
        });

    openNewTab(
      {
        title: fileName,
        icon,
        tabComponent,
        tooltip,
        props: {
          savedFile: fileName + '.' + fileType,
          savedFolder: 'archive:' + folderName,
          savedFormat: 'text',
          archiveFolder: folderName,
          ...connProps,
        },
      },
      { editor: resp }
    );
  }

  export const extractKey = data => data.fileName;
  export const createMatcher =
    filter =>
    ({ fileName }) =>
      filterName(filter, fileName);
  const ARCHIVE_ICONS = {
    'table.yaml': 'img table',
    'view.sql': 'img view',
    'proc.sql': 'img procedure',
    'func.sql': 'img function',
    'trigger.sql': 'img sql-file',
    'matview.sql': 'img view',
  };

  function getArchiveIcon(data) {
    if (data.fileType == 'jsonl') {
      return 'img archive';
    }
    return ARCHIVE_ICONS[data.fileType] ?? 'img anyfile';
  }
</script>

<script lang="ts">
  import _ from 'lodash';
  import { filterName } from 'dbgate-tools';
  import { showModal } from '../modals/modalTools';

  import { getExtensions } from '../stores';

  import createQuickExportMenu from '../utility/createQuickExportMenu';
  import { exportQuickExportFile } from '../utility/exportFileTools';
  import openNewTab from '../utility/openNewTab';
  import AppObjectCore from './AppObjectCore.svelte';
  import InputTextModal from '../modals/InputTextModal.svelte';
  import ConfirmModal from '../modals/ConfirmModal.svelte';
  import { apiCall } from '../utility/api';
  import { openImportExportTab } from '../utility/importExportTools';
  import { isProApp } from '../utility/proTools';
  import { _t } from '../translations';

  export let data;
  $: isZipped = data.folderName?.endsWith('.zip');

  const handleRename = () => {
    showModal(InputTextModal, {
      value: data.fileName,
      label: _t('archiveFile.newFileName', { defaultMessage: 'New file name' }),
      header: _t('archiveFile.renameFile', { defaultMessage: 'Rename file' }),
      onConfirm: newFile => {
        apiCall('archive/rename-file', {
          file: data.fileName,
          folder: data.folderName,
          fileType: data.fileType,
          newFile,
        });
      },
    });
  };

  const handleDelete = () => {
    showModal(ConfirmModal, {
      message: _t('archiveFile.deleteFileConfirm', { defaultMessage: 'Really delete file {fileName}?', values: { fileName: data.fileName } }),
      onConfirm: () => {
        apiCall('archive/delete-file', {
          file: data.fileName,
          folder: data.folderName,
          fileType: data.fileType,
        });
      },
    });
  };
  const handleOpenArchive = () => {
    openArchive(data.fileName, data.folderName);
  };
  const handleClick = () => {
    if (!data.fileType) {
      return;
    }
    if (data.fileType == 'jsonl') {
      handleOpenArchive();
    }
    if (data.fileType.endsWith('.sql')) {
      handleOpenSqlFile();
    }
    if (data.fileType.endsWith('.yaml')) {
      handleOpenYamlFile();
    }
  };
  const handleOpenSqlFile = () => {
    openTextFile(data.fileName, data.fileType, data.folderName, 'QueryTab', 'img sql-file');
  };
  const handleOpenYamlFile = () => {
    openTextFile(data.fileName, data.fileType, data.folderName, 'YamlEditorTab', 'img yaml');
  };
  const handleOpenJsonLinesText = () => {
    openTextFile(data.fileName, data.fileType, data.folderName, 'JsonLinesEditorTab', 'img json');
  };

  function createMenu() {
    if (!data.fileType) {
      return [];
    }

    return [
      data.fileType == 'jsonl' && { text: _t('common.open', { defaultMessage: 'Open' }), onClick: handleOpenArchive },
      data.fileType == 'jsonl' && { text: _t('common.openInTextEditor', { defaultMessage: 'Open in text editor' }), onClick: handleOpenJsonLinesText },
      !isZipped && { text: _t('common.delete', { defaultMessage: 'Delete' }), onClick: handleDelete },
      !isZipped && { text: _t('common.rename', { defaultMessage: 'Rename' }), onClick: handleRename },
      data.fileType == 'jsonl' &&
        createQuickExportMenu(
          fmt => async () => {
            exportQuickExportFile(
              data.fileName,
              {
                functionName: 'archiveReader',
                props: {
                  fileName: data.fileName,
                  folderName: data.folderName,
                },
              },
              fmt
            );
          },
          {
            text: 'Export',
            onClick: () => {
              openImportExportTab({
                sourceStorageType: 'archive',
                sourceArchiveFolder: data.folderName,
                sourceList: [data.fileName],
              });

              // showModal(ImportExportModal, {
              //   initialValues: {
              //     sourceStorageType: 'archive',
              //     sourceArchiveFolder: data.folderName,
              //     sourceList: [data.fileName],
              //   },
              // });
            },
          }
        ),
      data.fileType.endsWith('.sql') && { text: _t('common.openSql', { defaultMessage: 'Open SQL' }), onClick: handleOpenSqlFile },
      data.fileType.endsWith('.yaml') && { text: _t('common.openYaml', { defaultMessage: 'Open YAML' }), onClick: handleOpenYamlFile },
      !isZipped &&
        isProApp() &&
        data.fileType == 'jsonl' && {
          text: _t('common.openInProfiler', { defaultMessage: 'Open in profiler' }),
          submenu: getExtensions()
            .drivers.filter(eng => eng.profilerFormatterFunction)
            .map(eng => ({
              text: eng.title,
              onClick: () => {
                openNewTab({
                  title: _t('common.profiler', { defaultMessage: 'Profiler' }),
                  icon: 'img profiler',
                  tabComponent: 'ProfilerTab',
                  props: {
                    jslidLoad: `archive://${data.folderName}/${data.fileName}`,
                    engine: eng.engine,
                    // profilerFormatterFunction: eng.profilerFormatterFunction,
                    // profilerTimestampFunction: eng.profilerTimestampFunction,
                    // profilerChartAggregateFunction: eng.profilerChartAggregateFunction,
                    // profilerChartMeasures: eng.profilerChartMeasures,
                  },
                });
              },
            })),
        },
    ];
  }
</script>

<AppObjectCore
  {...$$restProps}
  {data}
  title={data.fileLabel}
  icon={getArchiveIcon(data)}
  menu={createMenu}
  on:click={handleClick}
/>
